package com.lvyp.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvyp.server.mapper.MailLogMapper;
import com.lvyp.server.pojo.*;
import com.lvyp.server.service.IEmployeeService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import com.lvyp.server.mapper.EmployeeMapper;
import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lvyp
 * @since 2021-04-24
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private MailLogMapper mailLogMapper;
    /**
     * 获取所有员工，分页显示
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public ResPageBean getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        Page<Employee> page = new Page<>(currentPage,size);  // 开启分页，传入当前页和大小
        IPage<Employee> employeeByPage = employeeMapper.getEmployeeByPage(page, employee, beginDateScope);
        // 传入总条数，和数据list
        ResPageBean resPageBean = new ResPageBean(employeeByPage.getTotal(),employeeByPage.getRecords());
        return resPageBean;
    }

    /**
     * 获取最大工号
     * @return
     */
    @Override
    public RespBean getMaxWorkId() {
        // 查询当前最大工号
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        // maps.get(0).get("max(workID)")获取值，还要加一需要先转为int再加
        // 先转toString，然后再转integer,然后加一，最后再转回string
        // %08d不足八位就补齐，防止乱码00000101
        String maxID = String.format("%08d", Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1);

        return RespBean.success(null,maxID);
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @Override
    public RespBean addEmployee(Employee employee) {
        // 处理employee中的合同期限，合同日期=合同开始时间 和
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        // 计算 开始时间 和 结束时间 差多少天
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        // 可能会除不尽所以保留两位小数
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        // 设置合同期限的值
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));

        // 添加员工，如果受影响行数=1，就是添加成功
        if (1 == employeeMapper.insert(employee)) {


            // 发送信息到消息队列
            Employee emp = employeeMapper.getEmployee(employee.getId()).get(0);

            //数据库记录发送的消息
            String msgId = UUID.randomUUID().toString();
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(emp.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setCount(0);
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogMapper.insert(mailLog);
            // 发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_QUEUE_NAME,  // 队列名
                    MailConstants.MAIL_ROUTING_KEY_NAME,  // 交换机名
                    emp,  // 消息
                    new CorrelationData(msgId));
            System.out.println("--------------->发送消息:"+emp);

            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    /**
     * 查询所有员工，如果传入id就是根据id查询员工，如果不传就查询所有
     * @param id
     * @return
     */
    @Override
    public List<Employee> getEmployee(Integer id) {
        return employeeMapper.getEmployee(id);
    }

    /**
     * 查询所有员工的账套
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public ResPageBean getEmployeeWithSalary(Integer currentPage, Integer size) {
        Page<Employee> page = new Page<>(currentPage,size);
        IPage<Employee> employeeIPage = employeeMapper.getEmployeeWithSalary(page);
        ResPageBean resPageBean = new ResPageBean(employeeIPage.getTotal(), employeeIPage.getRecords());


        return resPageBean;
    }
}
